"use strict";

const Compiler = require("webpack/lib/Compiler");
//const WebEnvironmentPlugin = require("webpack/lib/web/WebEnvironmentPlugin");
const WebEnvironmentPlugin = require("./web/WebEnvironmentPlugin");
const WebpackOptionsApply = require("webpack/lib/WebpackOptionsApply");
const WebpackOptionsDefaulter = require("webpack/lib/WebpackOptionsDefaulter");

function webpack(options, callback) {
	options = new WebpackOptionsDefaulter().process(options) || options;

	const compiler = new Compiler(options.context);
  compiler.options = options;
  // Polyfill for webpack3
  compiler.context = compiler.context || options.context

  new WebEnvironmentPlugin(
    options.inputFileSystem,
    options.outputFileSystem
  ).apply(compiler);

  if (options.plugins && Array.isArray(options.plugins)) {
    for (const plugin of options.plugins) {
      plugin.apply(compiler);
    }
  }
  compiler.hooks && compiler.hooks.environment.call();
  compiler.hooks && compiler.hooks.afterEnvironment.call();

  compiler.options = new WebpackOptionsApply().process(options, compiler);

  if (callback) {
		compiler.run(callback);
	}
	return compiler;
}
module.exports = webpack;

webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter;
webpack.WebpackOptionsApply = WebpackOptionsApply;
webpack.Compiler = Compiler;
webpack.WebEnvironmentPlugin = WebEnvironmentPlugin;
